package src.reflect;

import src.reflect.annotations.AutoRunClass;
import src.reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

public class Test6 {
        public static void main(String[] args)throws Exception {
                //1
                File dir = new File(Test6.class.getResource(".").toURI());
                String packageName = Test6.class.getPackage().getName();//根据Test6这个类获取它的包名
                //2
                File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
                for (File sub : subs) {
                        String fileName = sub.getName();
                        String className = fileName.substring(0, fileName.indexOf("."));
                        //3
                        Class cls = Class.forName(packageName + "." + className);
                        //根据类对象判断该类是否被注解AutoRunClass标注
                        boolean tf = cls.isAnnotationPresent(AutoRunClass.class);
                        if(cls.isAnnotationPresent(AutoRunClass.class)) {
                                System.out.println(className + ":被标注了");
                                //5
                                Object obj = cls.newInstance();//实例化该对象
                                //6
                                Method[] methods = cls.getDeclaredMethods();
                                for(Method method : methods){
                                        //7
                                        if(method.isAnnotationPresent(AutoRunMethod.class)){
                                                System.out.println(method.getName()+":被标注了");
                                                //通过方法对象获取在该方法上的注解@AutoRunMethod
                                                AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                                                int value = arm.value();//获取该注解的参数
                                                System.out.println("开始调用"+method.getName()+"()方法"+value+"次");
                                                for(int i=0;i<value;i++) {
                                                        method.invoke(obj);
                                                }
                                        }
                                }
                        }
                }

        }
}

